package com.tungse.juc.cas;

import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CAS_Demo {


    public static void main(String[] args) {
        AtomicStampedReference<Integer> asr = new AtomicStampedReference<>(1, 1);

        new Thread(()->{
            int stamp = asr.getStamp();
            System.out.println("a1->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("a=> 1-2  " + asr.compareAndSet(1, 2, stamp, stamp + 1));
            System.out.println("a2->"+asr.getStamp());
            stamp += 1;
            System.out.println("a=> 2-1  " + asr.compareAndSet(2, 1, stamp, stamp + 1));
            System.out.println("a3->"+asr.getStamp());

        }).start();



        new Thread(()->{
            int stamp = asr.getStamp();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("b1->"+stamp);
            System.out.println("b=> 1-2  " + asr.compareAndSet(1, 2, stamp, stamp + 1));
            System.out.println("b2->"+asr.getStamp());
        }).start();
    }
}
